package com.zzh.test1;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * CAS + 版本号实现原子更新
 */
public class AtomicStampedReferenceDemo {
    public static void main(String[] args) {
        User alice = new User("Alice",18);
        // 原子更新 User 对象 + 版本号1
        AtomicStampedReference<User> atomicStampedReference = new AtomicStampedReference<>(alice, 1);
        System.out.println(atomicStampedReference.getReference() + "\t" + atomicStampedReference.getStamp());

        User zhz = new User("zhz",28);
        boolean b;
        // 预期alice 后 更新zhz 版本号是1 才能修改2 => 成功 true 失败 false
        b = atomicStampedReference.compareAndSet(alice, zhz, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
        System.out.println(b + "\t" + atomicStampedReference.getReference() + "\t" + atomicStampedReference.getStamp());


        b = atomicStampedReference.compareAndSet(alice, zhz, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
        System.out.println(b + "\t" + atomicStampedReference.getReference() + "\t" + atomicStampedReference.getStamp());


        //User{name='Alice', age=18}	1
        //true	User{name='zhz', age=28}	2
        //false	User{name='zhz', age=28}	2
    }
}
